#!/usr/bin/python3
# -*- coding: utf-8; tab-width: 4; indent-tabs-mode: t -*-

import os
import sys
import shutil
import tempfile
import argparse
sys.path.append('/usr/lib64/syncupd')
from gbs_util import GbsUtil
from gbs_param import GbsConst
from gbs_param import GbsParam
from gbs_daemon import GbsDaemon


# parse parameter
parseResult = None
if True:
    argParser = argparse.ArgumentParser()
    argParser.add_argument("--port", help="Specify port for control protocol.")
    argParser.add_argument("--pid-file", dest='pid_file', help="Specify location of a PID file.")
    argParser.add_argument("-d", "--debug-level", dest='debug_level',
                           choices=['CRITICAL', 'ERROR', 'WARNING', 'INFO', 'DEBUG'], default="INFO",
                           help="Set output debug message level")
    parseResult = argParser.parse_args()

param = GbsParam()
try:
    # fill GbsParam according to argument
    if parseResult.port is not None:
        param.ctrlPort = parseResult.port
    if parseResult.pid_file is not None:
        param.pidFile = parseResult.pid_file
    param.logLevel = parseResult.debug_level

    # create logDir
    os.makedirs(param.logDir, exist_ok=True)

    # create tmpDir
    param.tmpDir = tempfile.mkdtemp(prefix="syncupd-")
    GbsUtil.chown(param.tmpDir, GbsConst.user, GbsConst.group)

    # start server
    GbsDaemon(param).run()
finally:
    if param.tmpDir is not None and os.path.exists(param.tmpDir):
        shutil.rmtree(param.tmpDir)
    if os.path.exists(GbsConst.runDir):
        shutil.rmtree(GbsConst.runDir)
